package fi.hut.soberit.agilefant.reporting.controller;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.support.PropertyComparator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.sun.jersey.api.client.WebResource;

import fi.hut.soberit.agilefant.model.export.IterationTO;
import fi.hut.soberit.agilefant.model.export.ProjectTO;
import fi.hut.soberit.agilefant.model.export.Story;
import fi.hut.soberit.agilefant.reporting.communication.RemoteCommunicationBuilder;

@Controller
public class ProjectReportController {

  @Autowired
  private RemoteCommunicationBuilder rcb;
  
  @SuppressWarnings("unchecked")
  @RequestMapping("projectReport.htm")
  public ModelAndView projectReport(@RequestParam("id") Integer projectId) {
    ModelAndView mv = new ModelAndView();
    WebResource res = rcb.getResourceForUrl("/project/" + projectId);
    ProjectTO project = res.get(ProjectTO.class);
    
    List<IterationTO> iterations = project.getIterations().getIteration();
    Collections.sort(iterations, new PropertyComparator("objectId", true, true));
    
    mv.addObject("project", project);
    mv.addObject("iterations", iterations);
    mv.addObject("projectId", projectId);
    
    return mv;
  }
  
  @SuppressWarnings("unchecked")
  @RequestMapping("projectStories.htm")
  public ModelAndView projectStories(@RequestParam("id") Integer projectId) {
    ModelAndView mv = new ModelAndView();
    WebResource res = rcb.getResourceForUrl("/project/" + projectId);
    ProjectTO project = res.get(ProjectTO.class);
    
    List<Story> stories = project.getStories().getStory();
    Collections.sort(stories, new PropertyComparator("objectId", true, true));
    
    mv.addObject("project", project);
    mv.addObject("stories", stories);
    mv.addObject("projectId", projectId);
    
    return mv;
  }
  
}
